<?PHP
#
#   FILE:  index.php
#
#   Part of the Metavus digital collections platform
#   Copyright 2011-2022 Edward Almasy and Internet Scout Research Group
#   http://metavus.net
#
# @scout:phpstan

namespace Metavus;

use ScoutLib\ApplicationFramework;
use Metavus\Bootloader;

# if we are in maintenance mode
if (file_exists(".maintenance")) {
    # display maintenance page and exit
    header("HTTP/1.1 503 Service Unavailable");
    $MaintFile = "interface/default/MaintenanceMode.html";
    if (is_readable("local/".$MaintFile)) {
        include("local/".$MaintFile);
    } elseif (is_readable($MaintFile)) {
        include($MaintFile);
    } else {
        print "Briefly unavailable for scheduled maintenance."
                ."  Please check back in a minute.";
    }
    exit(0);
}

# make sure that output buffering is initially turned off
if (ob_get_level()) {
    ob_end_clean();
}

# if it appears that the software has not yet been installed
if (((!file_exists("local/config.php") && !file_exists("config.php"))
     || file_exists("NEWVERSION")) && file_exists("installmv.php")) {
    # jump to installation
    ?><html>
    <head><meta http-equiv="refresh" content="0; URL=installmv.php"></head>
    <body bgcolor="white"></body>
    </html><?PHP
    exit();
}

# if on plugin configuration page
$PluginCfgPages = [
    "Plugins",
    "PluginConfig",
    "PluginUninstall",
];

if (array_key_exists("P", $_GET) && in_array($_GET["P"], $PluginCfgPages)) {
    # ensure that plugin configurations are all loaded
    $GLOBALS["StartUpOpt_FORCE_PLUGIN_CONFIG_LOAD"] = true;
}

# set up operating environment
require_once("objects/Bootloader.php");

$BootLoader = Bootloader::getInstance();
$BootLoader->boot();
# use the home page as the default page to load
$Page = "Home";

# if the page was specified as part of the URL
if (isset($_GET["P"])) {
    $Page = $_GET["P"];
# else if the URL was rewritten
} elseif (ApplicationFramework::wasUrlRewritten()) {
    # default to 404 error page (this may be overriden by clean URLs)
    $Page = "404";
}

# add any configured site keywords to page
$SysConfig = SystemConfiguration::getInstance();
$SiteKeywords = trim($SysConfig->getString("SiteKeywords"));
if (strlen($SiteKeywords)) {
    $GLOBALS["AF"]->addMetaTagOnce([
        "name" => "keywords",
        "content" => $SiteKeywords,
    ]);
}

# retrieve user currently logged in
$User = User::getCurrentUser();

# retrieve whether user is currently logged in
$IsLoggedIn = $User->isLoggedIn();

if ($IsLoggedIn && !ApplicationFramework::reachedViaAjax()) {
    $GLOBALS["AF"]->sessionInUse(true);
}

# make sure target page is at least somewhat valid
if (!is_string($Page)) {
    $Page = "Home";
}
# tell application framework to load page
$GLOBALS["AF"]->loadPage($Page);

# update user location
if ($IsLoggedIn && !ApplicationFramework::reachedViaAjax()) {
    $User->lastLocation($GLOBALS["AF"]->getPageName());
}
